package _thread_lock._futurepattern._future;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: huangya
 * @Date: 2020/10/19
 * @Description:
 */
public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {

    private final static String FUTURE_THREAD_PREFIX = "FUTURE-";

    private final AtomicInteger nextCounter = new AtomicInteger(0);

    /**
     *
     * @return
     */
    private String getNextName(){
        return FUTURE_THREAD_PREFIX + nextCounter.getAndIncrement();
    }

    /**
     * 提交不需要返回值的任务，Future.get()方法返回的将是null
     * @param runnable
     * @return
     */
    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Void> future = new FutureTask<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                runnable.run();
                //任务执行结束之后将null作为结果传给future
                future.finish(null);
            }
        }, getNextName()).start();
        return future;
    }

    /**
     * 提交需要返回值的任务，其中Task接口代替了Runnable接口
     * @param task
     * @param input
     * @return
     */
    @Override
    public Future<OUT> submit(Task<IN, OUT> task, IN input) {
        final FutureTask<OUT> future = new FutureTask<>();
        new Thread(() -> {
            OUT result = task.get(input);
            //任务执行结束之后，将真实的结果通过finish方法传递给future
            future.finish(result);
        }, getNextName()).start();
        return future;
    }
}
